%% Author: yun.xie
%% Created: Jan 21, 2012
%% Description: TODO: Add description to db_mgr
-module(db_mgr).
-include("rec_dec.hrl").
-include_lib("stdlib/include/qlc.hrl").

%%
%% Include files
%%

%%
%% Exported Functions
%%
-export([start/0,create/0,write/2,create_table/2,create_table/3,check_table/1,get/1,del/2,get/2,read/2,drop_table/1,do_transaction/1,build_schema/0]).

%%
%% API Functions
%%
start() ->
	mnesia:start().
%%	case mnesia:schema() of
%%	ok ->
%%		ok;
%%	_ ->
%%		create()
%%	end.

create() ->
	mnesia:create_schema([node()]).
%%
%% Local Functions
%%

write(Tab,Row) ->
	F= fun() ->
		mnesia:write(Tab, Row, write)
	end,
	io:format("save ~p in table ~p ~n",[Row, Tab]),
	case mnesia:transaction(F) of
	{atomic,ReturnS} ->
		Row;
	{aborted,_} ->
		error
	end.
	
get(T) ->
	Qry = qlc:q([X||X <- mnesia:table(T)]),
	F = fun() -> qlc:e(Qry) end,
	do_transaction(F).

get(qlc_st,Qry) ->
	F = fun() -> qlc:e(Qry) end,
	do_transaction(F);
	
get(T,Id) ->
	F = fun() ->
		mnesia:read(T,Id)
	end,
	do_transaction(F).
	

read(T,ID) ->
	F = fun() -> read(T,ID) end,
	mnesia:transaction(F).
	
del(T,ID) ->
	F = fun() -> mnesia:delete({T,ID}) end,
	io:format("delete ~p~n",[ID]),
	do_transaction(F).

check_table(T) ->
	case mnesia:wait_for_tables([T],1000) of
	ok ->
		ok;
	{timeout,_} ->
		no_found
	end.
do_transaction(F) ->
	case mnesia:transaction(F) of
	{atomic,ReturnS} ->
		ReturnS;
	{aborted,_} ->
		[]
	end.
drop_table(T) ->
	mnesia:delete_table(T).
create_table(T,FieldsOfT) ->
	create_table(T,FieldsOfT,[]).
	
create_table(T,FieldsOfT,A) ->
	case mnesia:create_table(T,
				[
				 {disc_copies,[node()]},
			 	 {attributes,FieldsOfT}
				] ++ A
			) of
	{atomic, ok} ->
		ok;
	{aborted, Reason} ->
		{error,Reason}
	end.
build_schema() ->
	mnesia:stop(),
	mnesia:create_schema([node()]).
%%	
%% (mnesiatest@host)3> mnesia:stop().
%%  ...
%% (mnesiatest@host)4> mnesia:create_schema([node()]).
%% ok
%% (mnesiatest@host)5> mnesia:start().
%% ok
%% (mnesiatest@host)6> mnesia:info().
%%  ...
%%  opt_disc. Directory "/home/user/test/db" is used. 
